/**
* ZookeeperWatcher.java 2020/5/21 4:11 下午
* Copyright ©2020 www.treefinance.com.cn All rights reserved.
* PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
package configcenter.zookeeper.primary.server;

import common.util.NetUtils;
import java.util.concurrent.CountDownLatch;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * File：ZookeeperWatcher.java<br>
 * Title: <br>
 * Description: <br>
 * Company: www.treefinance.com.cn <br>
 * @author heyouchi
 * Date: 2020/5/21
 */
public class ZookeeperWatcher implements Watcher {

  private static final Logger logger = LoggerFactory.getLogger(ZookeeperWatcher.class);

  private CountDownLatch countDownLatch;

  private ZookeeperServer zookeeperServer;

  public ZookeeperWatcher(CountDownLatch countDownLatch, ZookeeperServer zookeeperServer) {
    this.countDownLatch = countDownLatch;
    this.zookeeperServer = zookeeperServer;
  }

  @Override
  public void process(WatchedEvent event) {
    if (Event.KeeperState.SyncConnected == event.getState ()) {
      logger.info ( "the service {} is SyncConnected!", NetUtils.getLocalHost() );
      zookeeperServer.setAvailable(true);
      countDownLatch.countDown ();
    }
    if (Event.KeeperState.Expired == event.getState ()) {
      logger.warn ( "the service {} is expired!", NetUtils.getLocalHost() );
      zookeeperServer.setAvailable(false);
      reConnected();
    }
    if (Event.KeeperState.Disconnected == event.getState ()) {
      zookeeperServer.setAvailable(false);
      logger.warn ( "the service {} is Disconnected!", NetUtils.getLocalHost() );
    }
  }

  private  void reConnected(){
    zookeeperServer.destroy ();
    try {
      //wait for the zk server start success!
      Thread.sleep ( 2000 );
    } catch (InterruptedException e) {
      logger.error ( e.getMessage (), e );
    }
    zookeeperServer.init();
  }
}
